package com.example.cloud.controller.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.exceptions.ClientException;
import com.example.cloud.model.business.reservation.Patient;
import com.example.cloud.model.config.SmsTemplate;
import com.example.cloud.model.dto.Result;
import com.example.cloud.service.basic.config.SmsTemplateService;
import com.example.cloud.service.business.reservation.PatientService;
import com.example.cloud.service.message.SmsService;
import com.example.cloud.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * Created by wt on 2018/12/29.
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private SmsTemplateService smsTemplateService;

    @Autowired
    private PatientService patientService;

    @PostMapping("/send/{templateId}")
    public Result send(@PathVariable Long templateId, @RequestBody List<Long> ids) throws ClientException {
        SmsTemplate t = smsTemplateService.findOne(templateId);
        if(t == null){
            return ResultUtil.fail("未查询到模板信息");
        }
        List<Patient> allPatients = patientService.findByIds(ids);
        List<Patient> patients = allPatients.stream().filter(p -> p.getPhone() != null && !"".equals(p.getPhone())).collect(toList());
        JSONArray phones = new JSONArray();
        for (Patient p : patients) {
            phones.add(p.getPhone());
        }
        smsService.SendBatch("SMS_123739068", JSON.toJSONString(phones), t.getAnalysisContent());
        return ResultUtil.success();
    }
}
